import React from 'react'
import { Button, Toast } from 'antd-mobile'
import { useSelector } from 'react-redux'
import { hasPermission, getPermissionDeniedMessage} from '../utils/permission'
import type { RootState } from '../store/types'

interface PermissionGuardProps {
  children: React.ReactNode
  operation: string
  fallback?: React.ReactNode
  showToast?: boolean
}

/**
 * 权限检查组件
 * 用于包装需要权限检查的功能，如果用户没有权限则显示fallback内容或提示
 */
const PermissionGuard: React.FC<PermissionGuardProps> = ({
  children,
  operation,
  fallback,
  showToast = true
}) => {
  const userEmail = useSelector((state: RootState) => state.info.email)
  
  // 如果没有登录，显示登录提示
  if (!userEmail) {
    return (
      <div className="permission-guard">
        {fallback || (
          <Button 
            size="mini" 
            color="default"
            onClick={() => {
              Toast.show('请先登录')
            }}
            style={{
              fontSize: '12px',
              padding: '2px 8px',
              height: '24px',
              backgroundColor: '#f5f5f5',
              color: '#999',
              borderColor: '#d9d9d9'
            }}
          >
            登录
          </Button>
        )}
      </div>
    )
  }
  
  // 检查权限
  if (hasPermission(userEmail, operation)) {
    return <>{children}</>
  }
  
  // 权限不足，显示fallback或默认提示
  const handlePermissionDenied = () => {
    if (showToast) {
      Toast.show(getPermissionDeniedMessage(operation))
    }
  }
  
  return (
    <div className="permission-guard">
      {fallback || (
        <Button 
          size="small" 
          color="default"
          onClick={handlePermissionDenied}
          style={{
            backgroundColor: '#f5f5f5',
            color: '#999',
            borderColor: '#d9d9d9'
          }}
        >
          暂无权限
        </Button>
      )}
    </div>
  )
}

export default PermissionGuard
